<template>
  <el-dialog
    v-model="dialogVisible"
    title="评论详情"
    width="700px"
    :before-close="handleClose"
  >
    <div v-if="comment" class="comment-detail">
      <!-- 用户信息 -->
      <div class="user-section">
        <el-card>
          <div class="user-header">
            <el-avatar
              :src="formatAvatarUrl(comment.userAvatar)"
              :size="60"
              fit="cover"
            >
              <template #default>
                <IconifyIconOnline icon="ep:user" />
              </template>
            </el-avatar>
            <div class="user-info">
              <h3>{{ comment.userNickName || comment.userName }}</h3>
              <div class="user-meta">
                <span>用户ID: {{ comment.userId }}</span>
                <span>IP地址: {{ comment.ipAddress }}</span>
              </div>
            </div>
            <div class="user-actions">
              <el-button size="small" @click="handleViewUserComments">
                查看用户评论
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 评论内容 -->
      <div class="content-section">
        <el-card>
          <template #header>
            <div class="content-header">
              <span>评论内容</span>
              <div class="content-meta">
                <el-tag :type="getStatusTagType(comment.status)">
                  {{ getStatusText(comment.status) }}
                </el-tag>
                <el-tag
                  v-if="CommentManagementUtils.toBool(comment.isSensitive)"
                  type="danger"
                >
                  {{ comment.sensitiveTypeText || "敏感内容" }}
                </el-tag>
              </div>
            </div>
          </template>
          <div class="comment-content">
            <p>{{ comment.content }}</p>
          </div>
        </el-card>
      </div>

      <!-- 评论信息 -->
      <div class="info-section">
        <el-card>
          <template #header>
            <span>评论信息</span>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="评论ID">
              {{ comment.id }}
            </el-descriptions-item>
            <el-descriptions-item label="文章ID">
              <el-link type="primary" @click="handleViewArticle">
                {{ comment.articleId }}
              </el-link>
            </el-descriptions-item>
            <el-descriptions-item label="父评论ID">
              {{ comment.parentId || "无" }}
            </el-descriptions-item>
            <el-descriptions-item label="根评论ID">
              {{ comment.rootId || "无" }}
            </el-descriptions-item>
            <el-descriptions-item label="评论层级">
              <el-tag type="info">L{{ comment.level }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="评论路径">
              {{ comment.path }}
            </el-descriptions-item>
            <el-descriptions-item label="点赞数">
              <span class="interaction-count">👍 {{ comment.likeCount }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="回复数">
              <span class="interaction-count">💬 {{ comment.replyCount }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDateTime(comment.createTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ formatDateTime(comment.updateTime) }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>

      <!-- 审核信息 -->
      <div v-if="comment.auditTime" class="audit-section">
        <el-card>
          <template #header>
            <span>审核信息</span>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="审核时间">
              {{ formatDateTime(comment.auditTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="审核人员">
              {{ comment.auditUserName || "系统" }}
            </el-descriptions-item>
            <el-descriptions-item label="审核备注">
              {{ comment.auditRemark || "无" }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>

      <!-- 操作区域 -->
      <div class="action-section">
        <el-card>
          <template #header>
            <span>操作</span>
          </template>
          <div class="action-buttons">
            <el-button
              v-if="comment.status === 0"
              type="success"
              @click="handleAudit(1)"
            >
              <el-icon><Select /></el-icon>
              审核通过
            </el-button>
            <el-button
              v-if="comment.status === 0"
              type="danger"
              @click="handleAudit(2)"
            >
              <el-icon><Close /></el-icon>
              审核拒绝
            </el-button>
            <el-button
              v-if="!CommentManagementUtils.toBool(comment.isSensitive)"
              type="warning"
              @click="handleMarkSensitive"
            >
              <el-icon><Warning /></el-icon>
              标记敏感
            </el-button>
            <el-button
              v-if="CommentManagementUtils.toBool(comment.isSensitive)"
              type="info"
              @click="handleUnmarkSensitive"
            >
              取消敏感标记
            </el-button>
            <el-button @click="handleBanUser">
              <el-icon><Lock /></el-icon>
              禁言用户
            </el-button>
            <el-button type="danger" @click="handleDelete">
              <el-icon><Delete /></el-icon>
              删除评论
            </el-button>
          </div>
        </el-card>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Select,
  Close,
  Warning,
  Lock,
  Delete,
  Refresh
} from "@element-plus/icons-vue";
import { IconifyIconOnline } from "@/components/ReIcon";
import {
  type CommentInfo,
  markSensitiveCommentApi,
  unmarkSensitiveCommentApi,
  batchOperateCommentsApi,
  CommentManagementUtils
} from "@/api/comment-management";

// Props
interface Props {
  visible: boolean;
  comment: CommentInfo | null;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  comment: null
});

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
  audit: [comment: CommentInfo, auditResult: 1 | 2];
  refresh: [];
  banUser: [userId: number, comment: CommentInfo];
}>();

// 响应式数据
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

// 方法
const handleClose = () => {
  dialogVisible.value = false;
};

const handleRefresh = () => {
  emit("refresh");
};

const handleAudit = (auditResult: 1 | 2) => {
  if (props.comment) {
    emit("audit", props.comment, auditResult);
  }
};

const handleMarkSensitive = async () => {
  if (!props.comment) return;

  try {
    await ElMessageBox.confirm("确定要将此评论标记为敏感内容吗？", "标记敏感", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const data = await markSensitiveCommentApi(props.comment.id, "违禁词");
    if (data.code === 200) {
      ElMessage.success("标记敏感成功");
      emit("refresh");
    } else {
      ElMessage.error(data.message || "标记敏感失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("标记敏感失败:", error);
      ElMessage.error("标记敏感失败");
    }
  }
};

const handleUnmarkSensitive = async () => {
  if (!props.comment) return;

  try {
    await ElMessageBox.confirm(
      "确定要取消此评论的敏感标记吗？",
      "取消敏感标记",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const data = await unmarkSensitiveCommentApi(props.comment.id);
    if (data.code === 200) {
      ElMessage.success("取消敏感标记成功");
      emit("refresh");
    } else {
      ElMessage.error(data.message || "取消敏感标记失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("取消敏感标记失败:", error);
      ElMessage.error("取消敏感标记失败");
    }
  }
};

const handleBanUser = () => {
  if (!props.comment) return;
  emit("banUser", props.comment.userId, props.comment);
};

const handleDelete = async () => {
  if (!props.comment) return;

  try {
    await ElMessageBox.confirm(
      "确定要删除此评论吗？删除后可以恢复。",
      "删除评论",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const data = await batchOperateCommentsApi({
      commentIds: [props.comment.id],
      operation: "delete",
      reason: "管理员删除"
    });

    if (data.code === 200) {
      ElMessage.success("删除评论成功");
      emit("refresh");
      // 关闭对话框
      emit("update:visible", false);
    } else {
      ElMessage.error(data.message || "删除评论失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除评论失败:", error);
      ElMessage.error("删除评论失败");
    }
  }
};

const handleViewUserComments = () => {
  ElMessage.info("查看用户评论功能待实现");
};

const handleViewArticle = () => {
  ElMessage.info("查看文章功能待实现");
};

// 工具方法
const getStatusText = (status: number) => {
  return CommentManagementUtils.getStatusText(status);
};

const getStatusTagType = (status: number) => {
  return CommentManagementUtils.getStatusTagType(status);
};

const formatDateTime = (time: string) => {
  if (!time) return "-";
  return new Date(time).toLocaleString();
};

// 格式化头像URL
const formatAvatarUrl = (url: string): string => {
  if (!url) return "";

  // 如果已经是完整URL，直接返回
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }

  // 如果是相对路径，添加基础URL
  const baseURL = import.meta.env.DEV
    ? "http://localhost:8081"
    : "http://localhost:8081";
  return baseURL + url;
};
</script>

<style scoped lang="scss">
.comment-detail {
  .user-section,
  .content-section,
  .info-section,
  .audit-section,
  .action-section {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .user-section {
    .user-header {
      display: flex;
      gap: 16px;
      align-items: center;

      .user-info {
        flex: 1;

        h3 {
          margin: 0 0 8px;
          color: #303133;
        }

        .user-meta {
          display: flex;
          gap: 16px;
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }

  .content-section {
    .content-header {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .content-meta {
        display: flex;
        gap: 8px;
      }
    }

    .comment-content {
      p {
        margin: 0;
        font-size: 16px;
        line-height: 1.8;
        color: #303133;
        word-break: break-word;
      }
    }
  }

  .info-section {
    .interaction-count {
      display: inline-flex;
      gap: 4px;
      align-items: center;
    }
  }

  .action-section {
    .action-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
    }
  }
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
